package com.example.core.utils;

import com.example.core.constants.JwtConstants;
import com.example.core.constants.SecurityConstants;
import com.example.core.constants.TokenConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;

import java.util.HashMap;
import java.util.Map;


public class JwtUtils {
//    @Value("${jwt.secret}")
//    private String secret;


    public static String secret = TokenConstants.SECRET;
    /**
     * ⽣成令牌
     *
     * @param claims 数据

     * @return 令牌
     */
//    public static String createToken(Map<String, Object> claims,String secret)
//    {
//        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
//    }



    public static String createToken(Map<String, Object> claims) {
        // String token = Jwts.builder().setHeaderParam("typ", "JWT").setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }
    /**
     * 从令牌中获取数据
     *
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public static String getUserId(Claims claims) {
        Object value = claims.get(JwtConstants.LOGIN_USER_ID);
        if (value == null) {
            return "";
        }
        return  value.toString();
    }

    public static String getUserKey(String token) {
        Claims claims = parseToken(token);
        return getValue(claims, SecurityConstants.USER_KEY);
    }


    public static String getValue(Claims claims, String key) {
        return Convert.toStr(claims.get(key), "");
    }


}